package com.neolix.watch.bluetooth;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

import com.neolix.watch.dao.RemindEvent;
import com.neolix.watch.domain.NotificationType;
import com.neolix.watch.domain.WeatherType;
import com.neolix.watch.util.ByteUtil;
import com.neolix.watch.util.Constant;

import org.joda.time.DateTime;

import java.util.Arrays;

import static com.neolix.watch.NeolixApplication.getInstance;
import static com.neolix.watch.domain.WeatherType.findCommandType;

public class BlueToothUtil {
    private static DateTime lastTelephoneTime = DateTime.now();

    public static boolean isEnable() {
        final BluetoothManager bluetoothManager =
                (BluetoothManager) getInstance().getSystemService(Context.BLUETOOTH_SERVICE);
        BluetoothAdapter bluetoothAdapter = bluetoothManager.getAdapter();

        return bluetoothAdapter.isEnabled();
    }

    public static void connectBluetooth(Activity activity) {
        if (!BlueToothUtil.isEnable()) {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            activity.startActivityForResult(enableBtIntent, Constant.REQUEST_ENABLE_BT);
        } else {
            connectDevice(activity);
        }
    }

//    public static void connectDevice(Activity activity) {
//        if (isNotBlank(getLastBluetoothDeviceAddress())) {
//            Intent enableBtIntent = new Intent(getInstance(), BluetoothConnectActivity.class);
//            enableBtIntent.putExtra(Constant.DEVICE_NAME, getLastBluetoothDeviceAddress());
//            activity.startActivityForResult(enableBtIntent, Constant.REQUEST_CONNECT_DEVICE);
//        } else {
//            Intent enableBtIntent = new Intent(getInstance(), BluetoothListActivity.class);
//            activity.startActivityForResult(enableBtIntent, Constant.REQUEST_SCAN_BLUETOOTH);
//        }
//    }

    public static void connectDevice(Activity activity) {
        Intent enableBtIntent = new Intent(getInstance(), BluetoothListActivity.class);
        activity.startActivityForResult(enableBtIntent, Constant.REQUEST_SCAN_BLUETOOTH);
    }

//    public static boolean syncDateTime(DateTime time) {
//        BluetoothGattCharacteristic characteristic = getCharacteristic(WatchCommandType.syncDateTime);
//        if (characteristic == null)
//            return false;
//
////        getInstance().bluetoothLeService.setCharacteristicNotification(characteristic, true);//设置为false面条也可以收到通知
//        characteristic.setWriteType(WRITE_TYPE_DEFAULT);
//
//        byte[] contentByte = new byte[7];
//        contentByte[0] = (byte) time.getYearOfCentury();//year of century
//        contentByte[1] = (byte) time.getMonthOfYear();//month
//        contentByte[2] = (byte) time.getDayOfMonth();//day
//        contentByte[3] = (byte) time.getDayOfWeek();//week
//        contentByte[4] = (byte) time.getHourOfDay();//hour
//        contentByte[5] = (byte) time.getMinuteOfHour();//minute
//        contentByte[6] = (byte) time.getSecondOfMinute();//second
//        characteristic.setValue(contentByte);
//
//        getInstance().bluetoothLeService.writeCharacteristic(characteristic);
//
//        return true;
//    }

    public static void syncDateTime(DateTime time) {
        byte[] contentByte = new byte[7];
        contentByte[0] = (byte) time.getYearOfCentury();//year of century
        contentByte[1] = (byte) time.getMonthOfYear();//month
        contentByte[2] = (byte) time.getDayOfMonth();//day
        contentByte[3] = (byte) time.getDayOfWeek();//week
        contentByte[4] = (byte) time.getHourOfDay();//hour
        contentByte[5] = (byte) time.getMinuteOfHour();//minute
        contentByte[6] = (byte) time.getSecondOfMinute();//second

        addBluetoothData(new BluetoothData(WatchCommandType.syncDateTime, contentByte));
    }

//    public static boolean syncWeather(String weatherInfo, int temperature) {
//        BluetoothGattCharacteristic characteristic = getCharacteristic(WatchCommandType.syncWeather);
//        if (characteristic == null)
//            return false;
//
////        getInstance().bluetoothLeService.setCharacteristicNotification(characteristic, true);//设置为false面条也可以收到通知
//        characteristic.setWriteType(WRITE_TYPE_DEFAULT);
//
//        WeatherType weatherType = findCommandType(weatherInfo);
//
//        byte[] firstByte = new byte[2];
//        byte[] contentByte;
//
//        firstByte[0] = (byte) weatherType.getWatchImageIndex();//天气对应的图片 需要根据天气去对应 测试阶段先默认2
//        firstByte[1] = (byte) temperature;
//
//        contentByte = weatherInfo.getBytes(Constant.GBK_CHARSET);
//
//        characteristic.setValue(ByteUtil.concat(firstByte, contentByte));
//        getInstance().bluetoothLeService.writeCharacteristic(characteristic);
//
//        return true;
//    }

    public static void syncWeather(String weatherInfo, int temperature) {
        WeatherType weatherType = findCommandType(weatherInfo);

        byte[] firstByte = new byte[2];
        byte[] contentByte;

        firstByte[0] = (byte) weatherType.getWatchImageIndex();//天气对应的图片 需要根据天气去对应 测试阶段先默认2
        firstByte[1] = (byte) temperature;

        contentByte = weatherInfo.getBytes(Constant.GBK_CHARSET);

        BluetoothData data = new BluetoothData(WatchCommandType.syncWeather, ByteUtil.concat(firstByte, contentByte));
        addBluetoothData(data);
    }

//    public static boolean syncRemindEvent(int operateType, RemindEvent event) {
//        BluetoothGattCharacteristic characteristic = getCharacteristic(WatchCommandType.syncRemindEvent);
//        if (characteristic == null)
//            return false;
//
////        getInstance().bluetoothLeService.setCharacteristicNotification(characteristic, true);//设置为false面条也可以收到通知
//        characteristic.setWriteType(WRITE_TYPE_DEFAULT);
//
//        byte[] firstByte;
//        byte[] contentByte;
//        if (operateType == 1) {
//            firstByte = new byte[2];
//            firstByte[0] = (byte) operateType;
//            firstByte[1] = (byte) event.getEventID();
//        } else {
//            DateTime time = new DateTime(event.getDateTime());
//            firstByte = new byte[7];
//            firstByte[0] = (byte) operateType;//type
//            firstByte[1] = (byte) event.getEventID();//type
//            firstByte[2] = (byte) time.getYearOfCentury();//year of century
//            firstByte[3] = (byte) time.getMonthOfYear();//month
//            firstByte[4] = (byte) time.getDayOfMonth();//day
//            firstByte[5] = (byte) time.getHourOfDay();//hour
//            firstByte[6] = (byte) time.getMinuteOfHour();//minute
//        }
//
//        contentByte = event.getContent().getBytes(Constant.GBK_CHARSET);
//        byte[] suffixByte = new byte[1];
//        suffixByte[0] = (byte) 0;
//
//        characteristic.setValue(ByteUtil.concatAll(firstByte, contentByte, suffixByte));
//        getInstance().bluetoothLeService.writeCharacteristic(characteristic);
//
//        return true;
//    }

    public static void syncRemindEvent(int operateType, RemindEvent event) {
        byte[] firstByte;
        byte[] contentByte;
        if (operateType == 1) {
            firstByte = new byte[2];
            firstByte[0] = (byte) operateType;
            firstByte[1] = (byte) event.getEventID();
        } else {
            DateTime time = new DateTime(event.getDateTime());
            firstByte = new byte[7];
            firstByte[0] = (byte) operateType;//type
            firstByte[1] = (byte) event.getEventID();//type
            firstByte[2] = (byte) time.getYearOfCentury();//year of century
            firstByte[3] = (byte) time.getMonthOfYear();//month
            firstByte[4] = (byte) time.getDayOfMonth();//day
            firstByte[5] = (byte) time.getHourOfDay();//hour
            firstByte[6] = (byte) time.getMinuteOfHour();//minute
        }

        contentByte = event.getContent().getBytes(Constant.GBK_CHARSET);
        byte[] suffixByte = new byte[1];
        suffixByte[0] = (byte) 0;

        BluetoothData data = new BluetoothData(WatchCommandType.syncRemindEvent, ByteUtil.concatAll(firstByte, contentByte, suffixByte));
        addBluetoothData(data);
    }

//    public static boolean syncNotification(NotificationType type, String owner, String content) {
//        if (lastTelephoneTime != null && type == NotificationType.TELPHONE && lastTelephoneTime.plusSeconds(2).isAfterNow()) {
//            return false;
//        }
//        if (type == NotificationType.TELPHONE)
//            lastTelephoneTime = DateTime.now();
//
//        BluetoothGattCharacteristic characteristic = getCharacteristic(WatchCommandType.syncNotification);
//        if (characteristic == null)
//            return false;
//
//
////        getInstance().bluetoothLeService.setCharacteristicNotification(characteristic, true);//设置为false面条也可以收到通知
//        characteristic.setWriteType(WRITE_TYPE_DEFAULT);
//
//        byte[] firstByte;
//        byte[] contentByte1;
//        byte[] contentByte2;
//        byte[] ownerByte = new byte[12];
//        byte[] contentByte;
//
//
//        DateTime time = DateTime.now();
//        firstByte = new byte[6];
//        firstByte[0] = type.getTypeByte();//type
//        firstByte[1] = (byte) time.getMonthOfYear();//month
//        firstByte[2] = (byte) time.getDayOfMonth();//day
//        firstByte[3] = (byte) time.getDayOfWeek();//week
//        firstByte[4] = (byte) time.getHourOfDay();//hour
//        firstByte[5] = (byte) time.getMinuteOfHour();//minute
//
//
//        contentByte1 = owner.getBytes(Constant.GBK_CHARSET);
//        for (int i = 0; i < contentByte1.length; i++) {
//            if (i > ownerByte.length - 1)
//                break;
//
//            ownerByte[i] = contentByte1[i];
//        }
//        ownerByte[11] = 0x00;
//
//
//        contentByte2 = content.getBytes(Constant.GBK_CHARSET);
//        int MAX_LEN = 20;
//        if (contentByte2.length <= MAX_LEN)
//            contentByte = contentByte2;
//        else
//            contentByte = Arrays.copyOf(contentByte2, MAX_LEN);
//
//
//        byte[] suffixByte = new byte[1];
//        suffixByte[0] = (byte) 0;
//
//        characteristic.setValue(ByteUtil.concatAll(firstByte, ownerByte, contentByte, suffixByte));
//        getInstance().bluetoothLeService.writeCharacteristic(characteristic);
//        return true;
//    }

    public static void syncNotification(NotificationType type, String owner, String content) {
        if (lastTelephoneTime != null && type == NotificationType.TELPHONE && lastTelephoneTime.plusSeconds(2).isAfterNow()) {
            return;
        }
        if (type == NotificationType.TELPHONE)
            lastTelephoneTime = DateTime.now();

        byte[] firstByte;
        byte[] contentByte1;
        byte[] contentByte2;
        byte[] ownerByte = new byte[12];
        byte[] contentByte;


        DateTime time = DateTime.now();
        firstByte = new byte[6];
        firstByte[0] = type.getTypeByte();//type
        firstByte[1] = (byte) time.getMonthOfYear();//month
        firstByte[2] = (byte) time.getDayOfMonth();//day
        firstByte[3] = (byte) time.getDayOfWeek();//week
        firstByte[4] = (byte) time.getHourOfDay();//hour
        firstByte[5] = (byte) time.getMinuteOfHour();//minute


        contentByte1 = owner.getBytes(Constant.GBK_CHARSET);
        for (int i = 0; i < contentByte1.length; i++) {
            if (i > ownerByte.length - 1)
                break;

            ownerByte[i] = contentByte1[i];
        }
        ownerByte[11] = 0x00;


        contentByte2 = content.getBytes(Constant.GBK_CHARSET);
        int MAX_LEN = 20;
        if (contentByte2.length <= MAX_LEN)
            contentByte = contentByte2;
        else
            contentByte = Arrays.copyOf(contentByte2, MAX_LEN);


        byte[] suffixByte = new byte[1];
        suffixByte[0] = (byte) 0;

        BluetoothData data = new BluetoothData(WatchCommandType.syncNotification, ByteUtil.concatAll(firstByte, ownerByte, contentByte, suffixByte));
        addBluetoothData(data);
    }

//    public static boolean syncWatchStyle(int type) {
//            BluetoothGattCharacteristic characteristic = getCharacteristic(WatchCommandType.syncWatchStyle);
//            if (characteristic == null)
//            return false;
//
////        getInstance().bluetoothLeService.setCharacteristicNotification(characteristic, true);//设置为false面条也可以收到通知
//        characteristic.setWriteType(WRITE_TYPE_DEFAULT);
//
//        byte[] firstByte = new byte[1];
//        firstByte[0] = (byte) type;
//
//        characteristic.setValue(firstByte);
//        getInstance().bluetoothLeService.writeCharacteristic(characteristic);
//
//        return true;
//    }

    public static void syncWatchStyle(int type) {
        byte[] firstByte = new byte[1];
        firstByte[0] = (byte) type;

        addBluetoothData(new BluetoothData(WatchCommandType.syncWatchStyle, firstByte));
    }

//    public static boolean syncActive(boolean isActive) {
//        BluetoothGattCharacteristic characteristic = getCharacteristic(WatchCommandType.syncActive);
//        if (characteristic == null)
//            return false;
//
////        getInstance().bluetoothLeService.setCharacteristicNotification(characteristic, true);//设置为false面条也可以收到通知
//        characteristic.setWriteType(WRITE_TYPE_DEFAULT);
//
//        byte[] firstByte = new byte[1];
//        firstByte[0] = (byte) (isActive ? 1 : 0);
//
//        characteristic.setValue(firstByte);
//        getInstance().bluetoothLeService.writeCharacteristic(characteristic);
//
//        return true;
//    }

    public static void syncActive(boolean isActive) {
        byte[] firstByte = new byte[1];
        firstByte[0] = (byte) (isActive ? 1 : 0);

        addBluetoothData(new BluetoothData(WatchCommandType.syncActive, firstByte));
    }

    public static void syncBluetoothName(String name) {
        int MAX_LEN = 20;
        byte[] contentByte;

        byte[] nameBytes = name.getBytes(Constant.GBK_CHARSET);
        if (nameBytes.length <= MAX_LEN) {
            contentByte = new byte[20];
            System.arraycopy(nameBytes, 0, contentByte, 0, nameBytes.length);
        } else
            contentByte = Arrays.copyOf(nameBytes, MAX_LEN);

        contentByte[19] = (byte) 0;
        addBluetoothData(new BluetoothData(WatchCommandType.syncBluetoothName, contentByte));
    }

    public static void enableCharacteristic() {
        //设置可以收到通知
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        BluetoothGattCharacteristic stepCharacteristic = getCharacteristic(WatchCommandType.syncSteps);
        if (stepCharacteristic != null)
            getInstance().bluetoothLeService.setCharacteristicNotification(stepCharacteristic, true);//设置可以收到通知

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        BluetoothGattCharacteristic activatedCharacteristic = getCharacteristic(WatchCommandType.syncActivated);
        if (activatedCharacteristic != null)
            getInstance().bluetoothLeService.setCharacteristicNotification(activatedCharacteristic, true);//设置可以收到通知
    }

    public static BluetoothGattCharacteristic getCharacteristic(WatchCommandType type) {
        BluetoothGattCharacteristic characteristic = null;
        if (!getInstance().isConnectWatch()) {
//            showText("未连接设备");
            return characteristic;
        }

        BluetoothGattService service = getInstance().bluetoothLeService.getService(type.getServiceUUID());
        if (service != null) {
            characteristic = getInstance().bluetoothLeService.getCharacteristic(service, type.getCharacteristicUUID());
            if (characteristic == null) {
                Log.i(Constant.BLUETOOTH_TAG, "characteristic uuid not support " + type.getCharacteristicUUID());
//                showText("characteristic uuid not support");
                return characteristic;
            }
        } else {
//            showText("server uuid not support");
            Log.i(Constant.BLUETOOTH_TAG, "server uuid not support " + type.getServiceUUID());
            return characteristic;
        }
        return characteristic;
    }

    private static void addBluetoothData(BluetoothData data) {
        BluetoothLeService bluetoothLeService = getInstance().bluetoothLeService;
        if (bluetoothLeService == null)
            return;
        bluetoothLeService.addBluetoothData(data);
    }
}
